<template>
	<view>
		<view class="content">
			<scroll-view class="msg-list" style="bottom:30upx" scroll-y="true" :scroll-with-animation="scrollAnimation"
			 :scroll-top="scrollTop" :scroll-into-view="scrollToView" @scrolltoupper="loadHistory" upper-threshold="50">
				<!-- 加载历史数据waitingUI -->
				<view v-show="isHistoryLoading" class="loading">
					<view class="spinner">
						<view class="rect1"></view>
						<view class="rect2"></view>
						<view class="rect3"></view>
						<view class="rect4"></view>
						<view class="rect5"></view>
					</view>
				</view>
				<tui-card @click="goTarget(item)" class="dialogueItem" hover-class="dialogueItem-active" :id="'msg_'+item.d_id"
				 v-for="(item,index) in msgList" :key="item.d_id" :image="{url:item.d_userIcon}" :tag="{text:item.d_content.type_name}"
				 :title="{text:item.d_content.title}">
					<template v-slot:body>
						<view class="itemContent">
							{{item.d_content.content}}
						</view>
					</template>
					<template v-slot:footer>
						<view class=" itemContent">
							<span class="time">{{item.d_time |dateFormat("YYYY-MM-DD HH:mm")}}</span>
							<span>点击查看详情</span>
						</view>
					</template>
				</tui-card>
			</scroll-view>

		</view>
	</view>

</template>

<script>
	import {
		user,
		DB,
		tools,
		interFace
	} from '@/common/framework';
	export default {
		data() {
			return {
				curUserInfo:{},
				db: DB.init('push-msg'),
				topic: {},
				//文字消息
				textMsg: '',
				//消息列表
				isHistoryLoading: false,
				scrollAnimation: false,
				scrollTop: 0,
				scrollToView: '',
				msgList: [],
				lastMsgId: '',
				isLoadAllOver:false//是否全部加载完成

			}
		},
		onLoad(option) {
			this.topic = JSON.parse(decodeURIComponent(option.topic));
			this.curUserInfo=user.getUserInfo();
			// console.log(this.topic); 
			setTimeout(async () => {
				await this.getMsgList();
				await this.clearMsgUnReadStatus();
				this.bindEvent();
			}, 300);
			uni.setNavigationBarTitle({
				title:this.topic.t_title
			});

		},
		onShow() {
			this.scrollTop = 9999999;
		},
		onNavigationBarButtonTap(obj) {
			uni.navigateTo({
				url: '/pages/message/topic-setting/topic-setting?topic='+encodeURIComponent(JSON.stringify(this.topic))
			})
		},
		methods: {
			bindEvent() {
				uni.$on('onMessageArrived', (data) => {
					if(!data) return;
					 let t_id = tools.SHA1(data.sender.id + this.curUserInfo.userId);
					 if(t_id != this.topic.t_id){
						 return;
					 }
					 this.getMsgList();
					 
				});
				
				uni.$on('clearMessagesUnreadStatus',()=>{
					// this.msgList=splice(0,this.msgList.length);
				});
			
				
			},

			getDialogueItems(list) {
				list.forEach((item) => {
					item.d_content = JSON.parse(decodeURIComponent(item.d_content));
					switch (item.d_content.type) {
						case 11:
							item.d_content.type_name = "工作代办";
							break;
						case 12:
							item.d_content.type_name = "通知公告";
							break;
						case 13:
							item.d_content.type_name = "系统消息";
							break;
					}
				});
				return list;
			},
			
			//获取对话列表
			async getMsgList(isFlash, isLoadMore) {
				try {
					let pageSize = 5;
					let sql = "select * from dialogue_" + this.topic.t_id + " order by d_id desc limit 0, " + pageSize + " ";;
					let list = await this.db.selectSql(sql);
					this.msgList = this.getDialogueItems(list).sort((a, b) => {
						return a.d_id - b.d_id;
					});
					// 滚动到底部
					this.$nextTick(() => {
						//进入页面滚动到底部
						this.scrollTop = 9999;
						this.$nextTick(() => {
							this.scrollAnimation = true;
						});
					});

				} catch (err) {
					console.error(err);
				}

			},
			//读取历史
			async loadHistory() {
				try {
					if (this.isHistoryLoading || this.isLoadAllOver) {
						return;
					}
					this.isHistoryLoading = true; //参数作为进入请求标识，防止重复请求
					this.scrollAnimation = false; //关闭滑动动画
					this.lastMsgId = this.msgList[0].d_id; //记住第一个信息ID
					var sql = "select * from dialogue_" + this.topic.t_id + " where d_id<" + this.lastMsgId +
						" order by d_id desc limit 0, 5 ";
					let list = await this.db.selectSql(sql);
					this.isHistoryLoading = false;
					if(list && list.length>0){
						list = this.getDialogueItems(list);
						list.forEach((item)=>{
							this.msgList.unshift(item);
						})
						
						//这段代码很重要，不然每次加载历史数据都会跳到顶部
						this.$nextTick(function() {
							this.scrollToView = 'msg_'+this.lastMsgId;//跳转上次的第一行信息位置
							this.$nextTick(function() {
								this.scrollAnimation = true;//恢复滚动动画
							});
						});
						
					}else{
						this.isLoadAllOver=true;
					}
					
				} catch (err) {
					console.error(err);
				}

			},
			
			//清理未读数量标记
			async clearMsgUnReadStatus(){
				try{
					let sql="update topic set t_unReadCount=0 where t_id='"+this.topic.t_id+"'";
					let ret =await this.db.executeSql(sql);
					uni.$emit('clearMessagesUnreadStatus', {});
				}catch(err){
					console.error(err);
				}
				
			},
			
			goTarget(item) {
				console.log(item);
				let workInterFace = interFace.getInterface("work");
				switch(item.d_content.type){
					case 11://11.工作代办 12:通知公告 13:系统消息
					workInterFace.goDetailPage(item.d_content.msgId,item.d_content.label);
					break;
				}
				//tools.toast(JSON.stringify(item));
			},

			


		}
	}
</script>

<style lang="scss">
	@import "@/static/css/chat.scss";

	.dialogueItem {
		margin-top: 30upx;
	}

	.dialogueItem-active {
		background-color: $uni-bg-color-hover;
	}

	.dialogueItem .itemContent {
		padding: 20upx 30upx;
	}

	.dialogueItem .time {
		float: right;
	}
</style>
